package qiniufile

import (
	"context"
	"fmt"
	"os"
	"path"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/utils/uuidx"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type FetchUrlLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFetchUrlLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FetchUrlLogic {
	return &FetchUrlLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FetchUrlLogic) FetchUrl(req *types.FetchUrlReq) (resp *types.MediaFileInfoResp, err error) {
	var resUrl string = *req.Url

	// judge if the suffix is legal
	// 校验后缀是否合法
	dotIndex := strings.LastIndex(resUrl, ".")
	slashIndex := strings.LastIndex(resUrl, "/")
	if slashIndex == -1 {
		logx.Errorw("reject the file which does not have suffix")
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "file.wrongTypeError"))
	}
	var fileSuffix string
	if dotIndex == -1 || dotIndex < slashIndex {
		logx.Errorw("reject the file which does not have suffix")
	} else {
		fileSuffix = "." + resUrl[dotIndex+1:]
	}

	fileUUID := uuidx.NewUUID()
	var storeFileName string = fileUUID.String() + fileSuffix
	var fileType string = "other"
	timeString := time.Now().Format("200601")

	// generate path
	// 生成路径

	// judge if the file directory exists, if not create it. Both private and public need
	// to be created in order to move files when status changed
	// 判断文件夹是否已创建, 同时创建好私人和公开文件夹防止文件状态改变时无法移动

	publicStoreDir := path.Join(l.svcCtx.Config.NfsConf.PublicStorePath, fileType, timeString)
	privateStoreDir := path.Join(l.svcCtx.Config.NfsConf.PrivateStorePath, fileType, timeString)

	_, err = os.Stat(publicStoreDir)
	if err != nil {
		if os.IsNotExist(err) {
			if err = os.MkdirAll(publicStoreDir, 0775); err != nil {
				logx.Errorw("failed to create directory for storing public files", logx.Field("path", publicStoreDir))
				return nil, errorx.NewCodeError(errorcode.Internal,
					l.svcCtx.Trans.Trans(l.ctx, i18n.Failed))
			}
		} else {
			logx.Errorw("failed to parse directory for storing public files", logx.Field("path", publicStoreDir))
			return nil, errorx.NewCodeError(errorcode.Internal,
				l.svcCtx.Trans.Trans(l.ctx, i18n.Failed))
		}
	}

	_, err = os.Stat(privateStoreDir)
	if err != nil {
		if os.IsNotExist(err) {
			if err = os.MkdirAll(privateStoreDir, 0775); err != nil {
				logx.Errorw("failed to create directory for storing private files", logx.Field("path", privateStoreDir))
				return nil, errorx.NewCodeError(errorcode.Internal,
					l.svcCtx.Trans.Trans(l.ctx, i18n.Failed))
			}
		} else {
			logx.Errorw("failed to parse directory for storing private files", logx.Field("path", privateStoreDir))
			return nil, errorx.NewCodeError(errorcode.Internal,
				l.svcCtx.Trans.Trans(l.ctx, i18n.Failed))
		}
	}

	// default is public
	// 默认是公开的
	var relativeStorePath string =
		strings.TrimPrefix(strings.TrimPrefix(l.svcCtx.Config.NfsConf.PublicStorePath, l.svcCtx.Config.NfsConf.PathPrefix), "/static/")

	var key string = fmt.Sprintf("%s/%s/%s/%s", relativeStorePath, fileType, timeString, storeFileName)

	data, err := l.svcCtx.AttachmentRpc.BackendCreateRecord(l.ctx, &attachmentclient.RecordInfo{
		Url:      &resUrl,
		Key:      &key,
		Diagnose: req.Diagnose,
	})
	if err != nil {
		return nil, err
	}

	if data.Id == nil {
		return &types.MediaFileInfoResp{
			BaseDataInfo: types.BaseDataInfo{
				Msg: l.svcCtx.Trans.Trans(l.ctx, i18n.Failed),
			},
		}, nil
	}

	var url string
	if data.Key != nil && len(*data.Key) > 0 {
		url = fmt.Sprintf("%s/%s", l.svcCtx.Config.NfsConf.StaticUrl, *data.Key)
	}

	var status uint32
	if data.DelStatus != nil && *data.DelStatus > 0 {
		status = uint32(globalkey.PostStatusTrash)
	} else if data.Status != nil && *data.Status > 0 {
		status = uint32(globalkey.PostStatusDraft)
	} else {
		status = uint32(globalkey.PostStatusPublish)
	}

	return &types.MediaFileInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.MediaFileInfo{
			BaseUUIDInfo: types.BaseUUIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.ExpiredAt,
			},
			UserId:        data.EndUser,
			ParentId:      data.ParentId,
			Url:           &url,
			Bucket:        data.Bucket,
			FileType:      data.Type,
			MimeType:      data.MimeType,
			Status:        &status,
			Path:          data.Key,
			RestoreStatus: data.RestoreStatus,
			Size:          data.Size,
			Md5:           data.Md5,
			MetaValue:     data.MetaValue,
		},
	}, nil
}
